<template>

  <div class="row-main">
    <el-button type="shenda" size="mini"   @click="initData" icon="el-icon-refresh">刷新数据</el-button>
    <el-button type="shenda" size="mini"   @click="addNewNotice" icon="el-icon-plus" >添加套餐</el-button>
    <el-table
      :data="tableData"
      class="row-main-table"
      ref="mainDataTable"
      :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
      v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)"
    >
      <el-table-column prop="detailName" label="套餐名称" align="center"></el-table-column>
      <el-table-column prop="price_show" label="金额" align="center"></el-table-column>
      <el-table-column prop="afterDiscountPrice_show" label="折扣后金额" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="{ row, rowIndex }">
          <el-dropdown trigger="click">
            <div>
              <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item><el-button class="operation" style="width: 100%;" @click="editEvent(row)">编辑</el-button></el-dropdown-item>
              <el-dropdown-item><el-button class="operation" style="width: 100%;" @click="deleteNoticeConfirm(row)">删除</el-button></el-dropdown-item>
              <el-dropdown-item><el-button class="operation" style="width: 100%;" @click="updateSeq(row)">修改排序</el-button></el-dropdown-item>
              <!-- <el-button class="operation" style="width: 100%;" @click="updateStatus(row)" v-if="row.dictIsUsed==='C_YES'">禁用</el-button>
              <el-button class="operation" style="width: 100%;" @click="updateStatus(row)" v-if="row.dictIsUsed==='C_NO'">启用</el-button> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div :style="{'overflow':$store.state.app.screenWidth<992?'scroll':'auto'}">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="row-main-pager"
        :current-page.sync="page.current"
        :page-size="page.size"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        background></el-pagination>
    </div>
    <el-footer height="0"></el-footer>
    <el-drawer
      class="drawer_form"
      size="60%"
      :title="noticeTitle"
      :visible.sync="drawer"
      direction="ttb"
      :before-close="handleClose"
    >
      <div class="sd-drawer-content notice_drawer_form custom_drawer_content">
        <div class="sd-drawer-content-pannel">
          <el-form ref="saveInfo" :model="saveInfo" :rules="formRules">
            <el-row>
              <el-col :xl="{ span: 20, push: 2 }" :lg="{ span: 20, push: 2 }">
                <el-form-item label="套餐名称:" label-width="120px" prop="detailName">
                  <el-input
                    size="small"
                    v-model="saveInfo.detailName"
                    style="width: 100%;"
                    placeholder="请输入套餐名称"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="{ span: 20, push: 2 }" :lg="{ span: 20, push: 2 }">
                <el-form-item label="金额:" label-width="120px" prop="price" :rules=" [{ required: true, message: '请填写金额', trigger: 'blur'},
          { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,message: '格式：最多两位小数,不可以输入负数', trigger: 'blur'}]">
                  <el-input
                    size="small"
                    v-model.trim="saveInfo.price"
                    style="width: 100%;"
                    placeholder="请输入金额"
                  > <template slot="append">元</template></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="{ span: 20, push: 2 }" :lg="{ span: 20, push: 2 }">
                <el-form-item label="折扣后金额:" label-width="120px" prop="afterDiscountPrice" :rules=" [{ required: true, message: '请填写折扣后金额', trigger: 'blur'},
          { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,message: '格式：最多两位小数,不可以输入负数', trigger: 'blur'}]">
                  <el-input
                    size="small"
                    v-model.trim="saveInfo.afterDiscountPrice"
                    style="width: 100%;"
                    placeholder="请输入折扣后金额"
                  ><template slot="append">元</template></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row>
             <el-col :xl="{ span: 20, push: 2 }" :lg="{ span: 20, push: 2 }">
               <el-form-item label="是否启用:" label-width="120px" prop="dictIsUsed">
                 <el-select
                   size="small"
                   placeholder="请选择是否启用"
                   style="width: 100%;"
                   v-model="saveInfo.dictIsUsed"
                 >
                   <el-option value="C_YES" label="启用"></el-option>
                   <el-option value="C_NO" label="禁用"></el-option>
                 </el-select>
               </el-form-item>
             </el-col>
           </el-row> -->
          </el-form>
        </div>
      </div>
      <div class="sd-drawer-footer">
        <div class="buttons">
          <el-button
            @click="submitHandle('saveInfo')"
            size="small"
            type="primary"
            style="margin-left: 10px"
            v-preventReClick
          >提交
          </el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      class="delete"
      top="33vh"
      :visible.sync="deleteNoticeVisible"
      :append-to-body="true"
      width="30%"
    >
      <span style="display: flex; justify-content: center;">确定删除【<span v-text="deleteRow.detailName" class="click_text"></span>】套餐</span>
      <span class="dialog-footer" slot="footer">
        <el-button @click="deleteNoticeVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="deleteNoticeFunc()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getbalanceDetailsList, deletebalanceDetail, saveBalanceDetail,
    togglebalanceDetailStatus// M26
  } from '@/api/getData'

  export default {
    name: "rowOneIndex",
    data() {
      return {
        deleteRow: {},
        noticeTitle: '',
        deleteNoticeVisible: false,
        // 新增、修改-数据对象
        saveInfo: {
          headId: '',
          detailName: "",
          price: "",
          afterDiscountPrice: "",
          // dictIsUsed:'C_YES'
        },
        drawer: false,

        form: {},
        value: false,
        maxPage: 1,
        tableData: [],
        pageSize: 10,
        currentPage: 1,
        tableLoading: false,
        headerId: '',
        page: {
          current: 1,
          size: 10,
          total: 0,
          ascs: [],
          descs: []
        },
        tablePage: {
          pageSize: 15,
          pageSizes: [5, 15, 20, 50, 100, 200, 500, 1000]
        },
        formRules: {
          detailName: [{required: true, message: "请输入套餐名称", trigger: "blur"}],
          price: [{required: true, message: "折扣后金额", trigger: "blur"}],
          afterDiscountPrice: [{required: true, message: "请输入折扣后金额", trigger: "blur"}],
          dictIsUsed: [
            {required: true, message: "请选择是否启用", trigger: "change"}
          ]
        },
        pagekey:''
      }
    },
    created() {
      let h = this.$route.query.headerId;
      if (!h) {
        this.$router.push({path: '/road/roadList'})
      }
      this.headerId = h
      this.initData()
    },
    methods: {
      async initData() {
        const returnData = await getbalanceDetailsList({
            headId: this.headerId,
            page: {
              current: this.currentPage + '',
              size: this.pageSize + '',
              ascs: this.ascs,
              descs: this.descs
            }
          },
          {
            obj: this,
            key: 'tableLoading'
          })
        this.tableData = []
        if (returnData._result) {
          this.maxPage = Math.ceil(returnData.data.total / this.pageSize) // 分页的最大页数
          returnData.data.records.map(item => {
            const obj = {}
            obj.id = item.id
            obj.headId = item.headId
            obj.detailName = item.detailName // 小套餐名称
            obj.price_show = this.formatterCommafyPoint2(item.price) // 金额
            obj.price = item.price
            obj.afterDiscountPrice_show = this.formatterCommafyPoint2(item.afterDiscountPrice) //折扣后金额
            obj.afterDiscountPrice = item.afterDiscountPrice //折扣后金额
            // obj.dictIsUsed = item.dictIsUsed //是否启用   前端默认填写 C_YES
            // obj.dictIsUsedName = item.dictIsUsedName
            obj.seq = item.seq
            this.tableData.push(obj)
          })
          this.tableLoading = false
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleSizeChange(val){
        this.page.size = val;
        this.page.current = 1;
        this.initData();
      },
      handleCurrentChange(val){
        this.page.current = val;
        this.initData();
      },
      async deleteSetMeal(obj) {
        this.$confirm('您确定要执行此操作么, 是否继续?', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(async () => {
          let sos = await deletebalanceDetail({id: obj.id, headId: this.headerId});
          if (sos._result) {

            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.initData()
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作已取消'
          });
        });
      },
      async gotoAddBase() {
        this.$router.push({path: '/road/baseThreeSetMealAdd', query: {headerId: this.headerId}})
      },

      editSetMeal(obj) {
        this.$router.push({path: '/road/baseThreeSetMealAdd', query: {headerId: this.headerId, id: obj.id}});
      }, cancel() {
        this.$router.back(-1)
      },
      async updateSeq(data) {
        this.pagekey = await this.$getPageKey();
        this.$prompt('请输入排序号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[1-9]\d*$/,
          inputErrorMessage: '序号只能为非0正整数',
          inputValue: data.seq
        }).then(async ({value}) => {

          let a = await saveBalanceDetail({
            id: data.id,
            seq: value,
            officialPrice: data.officialPrice,
            ceilingPrice: data.ceilingPrice,
            oemCostPrice: data.oemCostPrice,
            pagekey: this.pagekey
          });
          if (a._result) {
            this.$message.success("操作成功！")
            this.initData();
          }
        }).catch(() => {
        });
      },
      updateStatus(row) {
        if (row.dictIsUsed === 'C_YES') {
          this.$confirm('您确定要禁用该套餐吗, 是否继续?', '提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          }).then(
            () => {
              this.saveUpdateStatus(row)
            }
          ).catch(() => {
            this.$message({
              type: 'info',
              message: '操作已取消'
            });
          });
        } else {
          this.$confirm('您确定要启用该套餐吗, 是否继续?', '提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          }).then(
            () => {
              this.saveUpdateStatus(row)
            }
          ).catch(() => {
            this.$message({
              type: 'info',
              message: '操作已取消'
            });
          });
        }
      },
      async saveUpdateStatus(row) {
        let newDictStattus = ''
        let message = ''
        switch (row.dictIsUsed) {
          case 'C_YES':
            newDictStattus = 'C_NO'
            message = '已禁用套餐'
            break;
          case 'C_NO':
            newDictStattus = 'C_YES'
            message = '已启用套餐'
            break;
        }
        // console.log(row)
        const returnData = await togglebalanceDetailStatus({
          id: row.id,
          dictIsUsed: newDictStattus
        });
        if (returnData._result) {
          this.$message.success(message);
          this.initData();
        }
      },
      formatterCommafyPoint2(cellValue) {
        if (cellValue === "--") {
          return "￥--";
        } else {
          return "￥" + XEUtils.commafy(cellValue, {digits: 2});
        }
      },
      handleCurrentChange({currentPage, pageSize}) {
        //console.log(`当前页: ${val}`)
        //this.currentPage = val
        this.page.current = currentPage;
        this.page.size = pageSize;
        this.homeAgentPageNumber();
      },
      // 新增
      async addNewNotice() {
        //this.pagekey = await this.$getPageKey();
        this.noticeTitle = "添加套餐";
        this.saveInfo = {
          headId: this.headerId,
          detailName: "",
          price: "",
          afterDiscountPrice: "",
          // dictIsUsed:'C_YES'
        };
        this.drawer = true;
        this.pagekey = await this.$getPageKey();
      },
      // 编辑
      async editEvent(row) {
        this.pagekey = await this.$getPageKey();
        this.noticeTitle = "编辑套餐";
        this.saveInfo = {
          id: row.id,
          detailName: row.detailName,
          price: row.price,
          afterDiscountPrice: row.afterDiscountPrice,
          // dictIsUsed: row.dictIsUsed,
        };
        this.drawer = true;
        // this.showEdit = true
      },
      // 保存-校验
      submitHandle(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            // console.log(this.saveInfo);
            this.saveNewNoticeFunc();
          } else {
            // console.log('error submit!!');
            return false;
          }
        });
      },
      // 保存-接口
      async saveNewNoticeFunc() {
        const returnData = await saveBalanceDetail(this.saveInfo,{ pagekey: this.pagekey });
        if (returnData._result) {
          this.$message.success("提交成功");
          this.initData();
          this.drawer = false;
        }
        this.pagekey = await this.$getPageKey();
      },
      // 删除
      deleteNoticeConfirm(row) {
        // console.log(row);
        this.deleteRow = row
        this.deleteNoticeVisible = true;
      },
      // 删除-接口
      async deleteNoticeFunc() {
        const returnData = await deletebalanceDetail({
          id: this.deleteRow.id
        });
        if (returnData._result) {
          this.$message.success("删除成功");
          this.deleteNoticeVisible = false;
          this.initData();
        }
      },
      // 关闭抽屉
      handleClose(done) {
        this.$confirm("确认关闭？")
          .then(_ => {
            console.log(123);
            done();
            this.$refs.saveInfo.clearValidate();
            this.$refs.saveInfo.resetprops();
            // this.saveInfo={
            //   title:'',
            //   contentText:'',
            //   sendNumber:'',
            //   expirationDate:'',
            //   dictNoticeType:'',
            //   clickNumber:'0'
            // }
          })
          .catch(_ => {
          });
      },
    }
  }
</script>

<style scoped lang="scss">
  .drawer_form {
    padding: 50px;
    overflow-y: auto;
    .custom_drawer_content {
      width: 90%;
    }
  }

  /deep/ .el-drawer.ttb {
    width: 500px;
    left: 50%;
    margin-left: -250px;
    /* right:50%; */
  }

  .topRow {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }

  .el-popper[x-placement^=bottom] {
    margin-right: -31px;
    box-shadow: 0px 0px 10px #888888;
    margin-left: 6px;

    .operation {
      border: 0;
      outline: none;
      display: block;
      text-align: center;
      margin: 0;
    }
  }

  .el-popper[x-placement^=top] {
    box-shadow: 0px 0px 10px #888888;
    margin-left: 6px;
    margin-right: -31px;

    button {
      display: block;
    }

    .operation {
      border: 0;
      outline: none;
      display: block;
      text-align: center;
      margin: 0;
    }
  }
</style>
